package com.ruoyi.book.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.book.domain.Chapter;
import com.ruoyi.book.service.IChapterService;
import com.ruoyi.utils.JsoupUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.book.domain.Fiction;
import com.ruoyi.book.service.IFictionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 电子书列表Controller
 * 
 * @author 沉睡
 * @date 2024-08-05
 */
@RestController
@RequestMapping("/book/fiction")
public class FictionController extends BaseController
{
    @Autowired
    private IFictionService fictionService;

    @Autowired
    private IChapterService chapterService;


    /**
     * 查询电子书列表列表
     */
    @PreAuthorize("@ss.hasPermi('book:fiction:list')")
    @GetMapping("/list")
    public TableDataInfo list(Fiction fiction)
    {
        startPage();
        List<Fiction> list = fictionService.selectFictionList(fiction);
        return getDataTable(list);
    }

    /**
     * 导出电子书列表列表
     */
    @PreAuthorize("@ss.hasPermi('book:fiction:export')")
    @Log(title = "电子书列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Fiction fiction)
    {
        List<Fiction> list = fictionService.selectFictionList(fiction);
        ExcelUtil<Fiction> util = new ExcelUtil<Fiction>(Fiction.class);
        util.exportExcel(response, list, "电子书列表数据");
    }

    /**
     * 获取电子书列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('book:fiction:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(fictionService.selectFictionById(id));
    }

    /**
     * 新增电子书列表
     */
    @PreAuthorize("@ss.hasPermi('book:fiction:add')")
    @Log(title = "电子书列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Fiction fiction)
    {
        return toAjax(fictionService.insertFiction(fiction));
    }

    /**
     * 修改电子书列表
     */
    @PreAuthorize("@ss.hasPermi('book:fiction:edit')")
    @Log(title = "电子书列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Fiction fiction)
    {
        return toAjax(fictionService.updateFiction(fiction));
    }

    /**
     * 删除电子书列表
     */
    @PreAuthorize("@ss.hasPermi('book:fiction:remove')")
    @Log(title = "电子书列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(fictionService.deleteFictionByIds(ids));
    }


    /**
     * 抓取电子书
     */
//    @PreAuthorize("@ss.hasPermi('book:fiction:crawlingBook')")
//    @Log(title = "抓取电子书", businessType = BusinessType.EXPORT)
//    @GetMapping("/crawlingBook")
//    public void crawlingBook()
//    {
//        String fictionURL = "https://www.477zw3.com/html/253/253214/";
//        //爬取小说基本信息
//        Fiction fiction = JsoupUtil.getFictions(JsoupUtil.getDoc(fictionURL));
//        if (fiction != null) {
//            Fiction fiction1 = fictionService.selectFictionByFictionName(fiction.getFictionName());
//            if (fiction1 == null) {
//                fictionService.insertFiction(fiction);
//
//                Document doc = JsoupUtil.getDoc(fictionURL);
//                Elements elements = doc.select(".box_con #list dl").get(1).getElementsByTag("a");
//                logger.info("小说章数：" + elements.size());
//
//                Chapter chapterContent = new Chapter();
//                chapterContent.setFictionId(fiction.getId());
//                for (int i = 0; i <  elements.size(); i++) {
//                    try {
//                        String url = "https://www.477zw3.com" + doc.select(".box_con #list dl").get(1).select("dd").get(i).select("a").attr("href");
//                        Document document = JsoupUtil.getDoc(url);
//                        //章节标题
//                        String title = document.select(".content_read .bookname h1").text();
//                        //章节内容
//                        String text = document.getElementById("content").html();
//                        //保存小说内容
//
//                        text.replaceAll("Ｗωw.Ч㈦7zw.cóm", "");
//                        text.replaceAll("M.④⑦七Ζw.℃om", "");
//                        text.replaceAll("网站即将关闭，下载星星阅读app为您提供大神李别浪的我爹绝对被人夺舍了", "");
//                        text.replaceAll("下载星星阅读app，阅读最新章节内容无广告免费", "");
//                        // 去掉此内容之后的所有数据 想要看最新章节内容，请下载星星阅读app，无广告免费阅读最新章节内容。网站已经不更新最新章节内容，已经星星阅读小说APP更新最新章节内容。
//                        text = text.substring(0, text.indexOf("想要看最新章节内容，请下载星星阅读app，无广告免费阅读最新章节内容。网站已经不更新最新章节内容，已经星星阅读小说APP更新最新章节内容。"));
//                        chapterContent.setContent(text);
//                        chapterContent.setChapterUrl(url);
//                        chapterContent.setChapterTitle(title);
//                        chapterContent.setSort(i + 1);
//                        chapterService.insertChapter(chapterContent);
//                        logger.info("抓取小说：" + fiction.getFictionName() + "" + title);
//                        // 暂停两秒
//                        Thread.sleep(5000);
//                    } catch (Exception e) {
//                        logger.error("抓取小说内容异常" + e);
//                    }
//                }
//                logger.info("抓取小说完成");
//
//
//            } else {
//                logger.info("这本小说已经保存到数据库");
//            }
//        } else {
//            logger.info("小说连接地址错误");
//        }
//
//    }

}
